import sys
import traceback
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QMessageBox
from PyQt5.QtCore import Qt

# 设置异常钩子
def exception_hook(exctype, value, traceback_obj):
    """全局异常处理"""
    error_msg = f"发生未捕获的异常:\n类型: {exctype.__name__}\n信息: {value}\n\n详细堆栈:\n"
    for line in traceback.format_tb(traceback_obj):
        error_msg += line
    
    print(error_msg)
    QMessageBox.critical(None, "系统错误", f"程序发生错误:\n{value}\n\n请检查日志文件获取详细信息。")
    sys.__excepthook__(exctype, value, traceback_obj)

sys.excepthook = exception_hook

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("人事管理系统1.0.1")
        self.setGeometry(100, 100, 1310, 800)
        self.init_ui()
    
    def init_ui(self):
        try:
            # 创建标签页
            self.tabs = QTabWidget()
            
            # 导入模块（延迟导入，避免循环引用）
            from employee_manager import EmployeeManager
            from leave_manager import LeaveManager
            
            # 人事信息管理标签页
            self.employee_tab = EmployeeManager()
            self.tabs.addTab(self.employee_tab, "人事信息管理")
            
            # 请假管理标签页
            self.leave_tab = LeaveManager("admin")
            self.tabs.addTab(self.leave_tab, "请假管理")
            
            self.setCentralWidget(self.tabs)
            
            # 状态栏
            self.statusBar().showMessage("系统就绪")
            
        except Exception as e:
            QMessageBox.critical(self, "初始化错误", f"界面初始化失败: {str(e)}")
            raise

def main():
    try:
        # 创建应用实例
        app = QApplication(sys.argv)
        app.setApplicationName("人事管理系统")
        app.setApplicationVersion("1.0.0")
        
        # 设置样式
        app.setStyle('Fusion')
        
        # 创建主窗口
        window = MainWindow()
        window.show()
        
        # 运行应用
        result = app.exec_()
        
        # 清理资源
        from database import Database
        db = Database()
        db.close_connections()
        
        sys.exit(result)
        
    except Exception as e:
        print(f"应用程序启动失败: {e}")
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()